<template>
  <div class="view">
    <DocumentEditor id="docEditor" :documentServerUrl="documentServerUrl" :config="officeConfig"/>
  </div>
  <div class="keywords">
    <span>关键词：</span>
    <el-tag v-for="keyword in keywords"
            :key="keyword.id"
            type="success"
            @click="searchByKeyword(keyword.value)"
    >
      {{ keyword.value }}
    </el-tag>
  </div>
  <div class="comment-container" v-if="true">
    <div class="comment-input">
      <el-input type="textarea" placeholder="评论内容" v-model="commentInformation.content" :autosize="{ minRows: 2, maxRows: 4 }" clearable/>
      <el-button type="primary" @click=postComment>评论</el-button>
    </div>
    <div class="table-data">
      <el-table :data="documentComments" :show-header="false" height="60vh">
        <el-table-column>
          <template #default="scope">
            <div class="comment-item">
              <p v-text="scope.row.content" style="background-color: blanchedalmond;padding: 10px;border-radius: 5px"/>
              <div style="display: flex;justify-content: space-between;">
                <span v-text="scope.row.username" />
                <span v-text="scope.row.createTime" style="right: 1px"/>
              </div>
              <el-button v-if="isSelfDocument" @click="deleteComment(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="pageSizes"
                     :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
                     @size-change="onChangePageSize"
                     @current-change="onChangePageNumber"/>
    </div>
  </div>
</template>

<script setup lang="ts">
import {DocumentEditor} from "@onlyoffice/document-editor-vue";
import {computed, onBeforeMount, onMounted, ref} from 'vue';
import getConfig from "../../utils/config.js";
import {getDocumentById} from "../../apis/DocumentApi.js"
import {elPrompt} from "../../utils/elPrompt.ts";
import {useRoute} from "vue-router";
import {Comment} from "../../interfaces/Comment.ts";
import {commentDelete, commentLoad, commentPost} from "../../apis/CommentApi.js"
import {Keyword} from "../../interfaces/Keyword.ts";
import {Document} from "../../interfaces/Document.ts";
import router from "../../router/router.js";
import {Result} from "../../interfaces/Result.ts";
import {PageDTO} from "../../interfaces/PageDTO.ts";
import {useUserStore} from "../../stores/userStore.ts";
import {User} from "../../interfaces/User.ts";
import {CommentDTO} from "../../interfaces/CommentDTO.ts";

onMounted(async () => {
  await init()
  await loadDocument()
  await loadComment()
})

async function init() {
  documentId = parseInt(<string>useRoute().params['documentId'])
  await useUserStore().getValue().then((user:User) => {
    userId = user.id
  })
  commentInformation.value.documentId = documentId
  commentInformation.value.userId = userId
  loginUserId.value = userId
}

//文档------------------------------------------------------
let documentId = 0
onBeforeMount(() => {
  documentId = parseInt(<string>useRoute().params.documentId)
})

const documentUserId = ref(0)
const loginUserId = ref(-1)
const isSelfDocument = computed( () => {
  return documentUserId.value === loginUserId.value
})
let userId = 0
const documentType = {
  djvu: 'word',
  doc: 'word',
  docm: 'word',
  docx: 'word',
  docxf: 'word',
  dot: 'word',
  dotm: 'word',
  dotx: 'word',
  epub: 'word',
  fb2: 'word',
  fodt: 'word',
  htm: 'word',
  html: 'word',
  mht: 'word',
  mhtml: 'word',
  odt: 'word',
  oform: 'word',
  ott: 'word',
  oxps: 'word',
  pdf: 'word',
  rtf: 'word',
  stw: 'word',
  sxw: 'word',
  txt: 'word',
  wps: 'word',
  wpt: 'word',
  xml: 'word',
  xps: 'word',
  csv: 'cell',
  et: 'cell',
  ett: 'cell',
  fods: 'cell',
  ods: 'cell',
  ots: 'cell',
  sxc: 'cell',
  xls: 'cell',
  xlsb: 'cell',
  xlsm: 'cell',
  xlsx: 'cell',
  xlt: 'cell',
  xltm: 'cell',
  xltx: 'cell',
  dps: 'slide',
  dpt: 'slide',
  fodp: 'slide',
  odp: 'slide',
  otp: 'slide',
  pot: 'slide',
  potm: 'slide',
  potx: 'slide',
  pps: 'slide',
  ppsm: 'slide',
  ppsx: 'slide',
  ppt: 'slide',
  pptm: 'slide',
  pptx: 'slide',
  sxi: 'slide',
};
const documentServerUrl = ref('http://localhost:8001')
const officeConfig = ref({
  documentType: "word",
  document: {
    fileType: "docx",
    title: "example.docx",
    url: "http://localhost:8080/document/download/0",
    permissions: {
      edit: false
    },
    editorConfig: {
      lang: 'zh'
    }
  }
});
const keywords = ref<Keyword[]>()

/**
 * 加载文档
 */
async function loadDocument() {
  let serverUrl = ''
  let config = {}
  await getConfig(result => {
    config = result
  })
  serverUrl = config['serverUrl']
  await getDocumentById(documentId, (result) => {
    if (result.status !== 200) return elPrompt(result.message, 'error')
    const document: Document = result.data
    documentUserId.value = document.userId
    keywords.value = document.keywords
    const title = document.title
    const fileType = title.slice(title.lastIndexOf('.') + 1)
    officeConfig.value.document.fileType = fileType
    officeConfig.value.documentType = documentType[fileType]
    let documentUrl = `${serverUrl}/document/download/${documentId}`
    const token = localStorage.getItem('token')
    if (token) documentUrl = `${documentUrl}?token=${token}`
    officeConfig.value.document.url = documentUrl
    officeConfig.value.document.title = title
  })
}

//评论------------------------------------------------------

const commentInformation = ref<Comment>({
  content:"",
  documentId:0,
  userId:0,
})
let documentComments = ref<Comment[]>([])
const pageSize = ref(2)
const pageNum = ref(1)
const total = ref(0)

const pageSizes = computed(() => {
  const numberArray = [10]
  let maxPageSize = numberArray[0]
  while (maxPageSize < total.value) {
    maxPageSize += 10
    numberArray.push(maxPageSize)
  }
  return numberArray
})

function onChangePageSize(value:number) {
  pageSize.value = value
  loadComment()
}

function onChangePageNumber(value:number) {
  pageNum.value = value
  loadComment()
}

async function postComment() {
  if(!commentInformation.value.content) return
  console.log(commentInformation.value)
  await commentPost(commentInformation.value,(result: Result<any>)=>{
    if (result.status !== 200) return elPrompt(result.message, "error")
    elPrompt('评论成功！', "success")
  })
  commentInformation.value.content = ""
  await loadComment()
}

async function loadComment() {
  await commentLoad(commentInformation.value.documentId, pageSize.value, pageNum.value, (result: Result<PageDTO<CommentDTO[]>>) => {
    if (result.status !== 200) return elPrompt(result.message, "error")
    total.value = result.data.total
    documentComments.value = result.data.dataLists
  })
}

async function deleteComment(comment: Comment) {
  await commentDelete(comment.id,(result: Result<any>)=> {
    if (result.status !== 200) return elPrompt(result.message, "error")
    documentComments.value = documentComments.value.filter((com) => {
      if (com.id !== comment.id) return com
    })
  })
  loadComment()
}

function searchByKeyword(keyword: string) {
  router.push({
    path: '/document/search',
    query: {
      searchKeyword: keyword
    }
  })
}
</script>

<style scoped>
.view {
  height: 100vh;
  width: 890px;
  margin: 0 auto;
  overflow: hidden;
}

.keywords {
  width: 890px;
  margin: 10px auto;
  border: solid 1px var(--color-info);
  border-radius: 5px;
  padding: 5px;
  box-sizing: border-box;

  .el-tag:hover {
    text-decoration: underline;
  }
}

.comment-container {
  width: 890px;
  height: 75vh;
  margin: 10px auto;
  border: solid 1px var(--color-info);
  border-radius: 5px;
  box-sizing: border-box;
  padding: 10px;

  .comment-input {
    display: flex;

    .el-input {
      height: 52px;
    }

    .el-button {
      margin-left: 10px;
      height: 36px;
      padding: 0 30px;
    }
  }

  .table-data {
    width: 100%;
    height: 63vh;
    .comment-item {
      background-color: #e5e5e5;
      border-radius: 5px;
      padding:10px;
      margin-top: 3px;
    }
  }

  .page {
    z-index: 100;
    background: white;
  }
}
</style>